const router = require('koa-router')();
const {mySqlHelper} = require('../../libs/index');
const cs4plScript = require('./scripts/cs4pl');

// 接口前缀
router.prefix('/api/cs4pl');

/**
 * 获取菜单信息.
 *
 * {:dbIndex} 数据库标识
 * {:schema} 数据库名称
 */
router.get('/:dbIndex/:schema/menus', async (ctx, next) => {
    let menuTypes;

    await mySqlHelper.queryForList(cs4plScript.PlatformMenuTypes, ctx.params, null, ctx.params.dbIndex).then(rs => {
        menuTypes = rs;
    }, reject => ctx.body = reject);

    await getPlatformRoles({ dbIndex: ctx.params.dbIndex, schema: ctx.params.schema }).then(rs => menuTypes.roles = (rs.datas || []).map(i => i.RoleName));

    if (menuTypes && menuTypes.datas) {
        let promises = menuTypes.datas.map(item => resolveMenusWithRights({
            schema: ctx.params.schema,
            dbIndex: ctx.params.dbIndex,
            menuType: item.Guid
        }, item));

        await Promise.all(promises).then(rses => {
            for (let index = 0; index < menuTypes.datas.length; index++) {
                menuTypes.datas[index].items = rses[index].datas;
            }
        }, reject => {
            console.log(reject);
        });
    }

    ctx.body = menuTypes;
});

let getPlatformRoles = roleQueryInfo => {
    return mySqlHelper.queryForList(cs4plScript.PlatformRoles, roleQueryInfo, roleQueryInfo.dbIndex);
};

let resolveMenusWithRights = menuQueryInfo => {
    return mySqlHelper.queryForList(cs4plScript.PlatformMenuDetails, menuQueryInfo, menuQueryInfo.dbIndex);
};

module.exports = router;